#!/usr/bin/env node

const program = require('commander');
const {
  exec
} = require('child_process');
const inquirer = require('inquirer');
const fs = require('fs');
const ora = require('ora');
const chalk = require('chalk');
const symbols = require('log-symbols');
const path = require('path');

program.version('1.0.0', '-v, --version')
  .command('init <name>')
  .action(name => {
    if (!fs.existsSync(name)) {
      inquirer.prompt([{
          name: 'description',
          message: '请输入项目的说明:'
        },
        {
          name: 'author',
          message: '请输入项目的作者:'
        },
        {
          name: 'type',
          type: 'list',
          message: '请选择导入方式:',
          choices: [
            "svn",
            "git"
          ]
        }
      ]).then(answers => {
        download(name, answers)
      })
    } else {
      console.log(symbols.error, chalk.red('项目已经存在此目录！'));
    }
  });

function download(name, answers) {
  const spinner = ora('正在下载。。。。。。');
  spinner.start();
  const type = answers.type
  delete answers.type
  if (type == 'svn') {
    try {
      exec('svn checkout svn://code.vlinkall.com/code/trunks/front_end/vlink-admin', {
        cwd: process.cwd()
      }, err => {
        if (err) {
          spinner.fail();
          console.log(symbols.error, chalk.red(err));
        } else {
          compilePackage(name, answers, spinner);
        }
      });
    } catch (e) {
      spinner.fail();
      console.log(symbols.error, chalk.red(e));
      console.log(symbols.info, chalk.blue('你的系统可能不支持svn指令'));
    }
  } else {
    try {
      exec('git clone git@192.168.1.230:vlink-web-project/vlink-admin.git', {
        cwd: process.cwd()
      }, err => {
        if (err) {
          spinner.fail();
          console.log(symbols.error, chalk.red(err));
        } else {
          compilePackage(name, answers, spinner);
        }
      })
    } catch (e) {
      spinner.fail();
      console.log(symbols.error, chalk.red(e));
      console.log(symbols.info, chalk.blue('你的系统可能不支持git指令'));
    }
  }
}

function compilePackage(name, answers, spinner) {
  try {
    fs.renameSync(path.join(process.cwd(), 'vlink-admin'), path.join(process.cwd(), name));
    const fileName = `${name}/package.json`;
    if (fs.existsSync(fileName)) {
      let packageStr = fs.readFileSync(fileName).toString();
      let packageObj = JSON.parse(packageStr);
      packageObj = Object.assign(packageObj, {
        name,
        ...answers
      });
      packageStr = JSON.stringify(packageObj);
      fs.writeFileSync(fileName, packageStr);
    } else {
      spinner.fail();
      console.log(symbols.error, chalk.red('文件下载失败！'));
      return;
    }
  } catch (e) {
    spinner.fail();
    console.log(symbols.error, chalk.red(e));
    return;
  }
  spinner.succeed();
  console.log(symbols.success, chalk.green('文件下载成功。'));
  installPackage(name);
}

function installPackage(name) {
  inquirer.prompt([{
    type: 'confirm',
    name: 'ifInstall',
    message: '你要现在下载依赖嘛?',
    default: true
  }]).then(({
    ifInstall
  }) => {
    if (ifInstall) {
      inquirer.prompt([{
        type: 'list',
        name: 'installWay',
        message: '请选择安装工具。',
        choices: [
          'npm', 'cnpm'
        ]
      }]).then(({
        installWay
      }) => {
        const spinner = ora('正在安装。。。。。。');
        spinner.start();
        if (installWay === 'npm') {
          installHelp(installWay, name, spinner);
        } else {
          exec('cnpm -v', err => {
            if (err) {
              exec('npm install -g cnpm --registry=https://registry.npm.taobao.org', err => {
                if (err) {
                  spinner.fail();
                  console.log(symbols.error, chalk.red(err));
                } else {
                  installHelp(installWay, name, spinner);
                }
              });
            } else {
              installHelp(installWay, name, spinner);
            }
          });
        }
      });
    } else {
      console.log(symbols.success, chalk.green('请自己安装好依赖。'));
      console.log(chalk.blue(`cd ./${name} && npm run serve 查看系统 @kaikai`));
    }
  })
}

function installHelp(type, name, spinner) {
  exec(`cd ./${name} && ${type} i`, err => {
    if (err) {
      spinner.fail();
      console.log(symbols.error, chalk.red(err));
    } else {
      spinner.succeed();
      console.log(symbols.success, chalk.green('依赖下载成功。'));
      console.log(chalk.blue(`cd ./${name} && npm run serve 查看系统 @kaikai。`));
    }
  });
}

program.parse(process.argv);